using Aurora.RabbitMq.Provider;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Aurora.RabbitMq;

/// <summary>
/// rabbitmq service extension
/// </summary>
public static class RabbitMqServiceExtension
{
    /// <summary>
    /// add rabbitmq 
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    public static void AddRabbitMq(this IServiceCollection services, IConfiguration configuration)
    {
        var configurationSection = configuration.GetSection("RabbitMQ");
        services.Configure<AuroraRabbitMqOptions>(configurationSection);
        services.Configure<AuroraRabbitMqOptions>(options =>
        {
            foreach (var connectionFactory in options.Connections.Values)
            {
                connectionFactory.DispatchConsumersAsync = true;
            }
        });
    }

    /// <summary>
    /// shutdown 
    /// </summary>
    /// <param name="app"></param>
    public static void OnApplicationShutdown(IApplicationBuilder app)
    {
        app.ApplicationServices.GetRequiredService<IChannelPool>().Dispose();
        app.ApplicationServices.GetRequiredService<IConnectionPool>().Dispose();
    }
}